﻿using System.IO.Compression;
using Microsoft.WindowsAzure;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using Wams.Admin;
using Microsoft.WindowsAzure.Storage.Blob;

namespace Wams.Server
{
    public static class FirstTimeSetup
    {
        public static WamsSettings DoIt()
        {
            Logger.Log(LogLevel.Warning, "Doing first time setup...");
            WamsSettings settings = PrepareSettingsFile();
            PrepareAdminSite();
            return settings;
        }


        public static void PrepareAdminSite()
        {
            CloudBlobClient blobClient = WamsCore.MainStorageAccount.CreateCloudBlobClient();
            CloudBlobContainer blobContainer = blobClient.GetContainerReference(WamsCore.ContainerName);
            string blobsPrefix = "Wams.Admin.UI";

            // Check if the Admin UI is installed.
            if (blobContainer.ListBlobs(blobsPrefix + "/", true).Any()) return;

            string urlToDownloadWamsClientUI = CloudConfigurationManager.GetSetting("Wams.AdminUIDownloadUrl");
            if (string.IsNullOrEmpty(urlToDownloadWamsClientUI)) urlToDownloadWamsClientUI = "https://kranzorg.blob.core.windows.net/public/WamsAdminUIPackage.v0.6.zip";
            WebRequest httpReq = HttpWebRequest.Create(new Uri(urlToDownloadWamsClientUI));

            try
            {
                using (WebResponse httpResp = httpReq.GetResponse())
                {
                    WamsInstances.InstallContent(WamsCore.MainStorageAccount, WamsCore.ContainerName, blobsPrefix, httpResp.GetResponseStream());
                }
                Logger.Log(LogLevel.Warning, "First time setup of admin site OK!");
            }
            catch (Exception ex)
            {
                Logger.Log(LogLevel.Warning, "Failed to do first time startup: " + ex.ToString());
            }           
            
        }

        public static WamsSettings PrepareSettingsFile()
        {
            WamsSettings settings = new WamsSettings();
            settings.Version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(4);

            settings.Modules.Add(new WamsModule()
            {
                ClassName = typeof(Comms).FullName,
                Name = "Wams Comms"
            });

            WamsSite adminSite = new WamsSite()
            {
                Id = 0,
                Name = "Wams.Admin.UI",
                Source = "Wams.Admin.UI",
            };
            adminSite.Bindings.Add(new WamsSiteBinding() { BindingInfo = "*:80:*" });
            settings.Sites.Add(adminSite);
            settings.SaveSettingsFile(WamsCore.MainStorageAccount, WamsCore.ContainerName);
            Logger.Log(LogLevel.Warning, "First time setup of settings file OK!");
            return settings;
        }
    }
}